//
//  ImageProcessViewController.m
//  PixelTest
//
//  Created by Han Guoxiang on 12-7-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ImageProcessViewController.h"
#import "ImageWorkedViewController.h"
#import "UIImage+Extension.h"
#import "ImageUtlity.h"
#import "AppDelegate.h"

@interface ImageProcessViewController () {
@private
}

-(void)updateControls;              //根据是否已经拍照，更新按钮的状态
-(void)isShowImageView:(BOOL)flag;  //是否显示承载图片的控件
-(void)btnClicked:(id)sender;       //主视图8个按钮的响应事件
-(void)showWorkViewAfterDelay;
-(void)hideImageView:(id)sender;               //隐藏显示的图片，恢复主界面


- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt;
@end
@implementation ImageProcessViewController

@synthesize permissions;
@synthesize hudView;
@synthesize btnSave,btnEmail,btnFacebook;
@synthesize mainScrollView;
@synthesize mainImgView;
@synthesize imgWorkedViewController;
@synthesize cameraOverLayer;
@synthesize btnClose;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:accessToken forKey:@"FBAccessTokenKey"];
    [defaults setObject:expiresAt forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
}

-(void)uploadPhoto
{
    self.hudView=[[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    [self.view addSubview:hudView];
    hudView.labelText=@"Uploading...";
    [hudView show:YES];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   mainImgView.image,@"picture", @"Taken with APScanner iPhone app",@"caption",
                                   nil];
    
    [[delegate facebook] requestWithGraphPath:@"me/photos"
                                    andParams:params
                                andHttpMethod:@"POST"
                                  andDelegate:self];
}
-(void)btnClicked:(id)sender
{
    NSString *overLayerName=@"cameraOverlayNeg.png";
    UIButton *btn=(UIButton *)sender;
    switch (btn.tag) {
        case 500:
        case 501:
        case 502:
        case 503:
        {
            UIImagePickerController *imagePicker=[[[UIImagePickerController alloc] init] autorelease];
            [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [imagePicker setDelegate:self];
            if(btn.tag==500)//Sliders
            {
                overLayerName=@"cameraOverlayslide.png";
                photoType=PhotoSlidersType;
            }
            if(btn.tag==501)//Neg
            {
                overLayerName=@"cameraOverlayNeg.png";
                photoType=PhotoNegativeType;
            }
            if(btn.tag==502)//35
            {
                overLayerName=@"cameraOverlaypos35.png";
                photoType=Photo35Type;
            }
            if(btn.tag==503)//46
            {
                overLayerName=@"cameraOverlaypos46.png";
                photoType=Photo46Type;
            }
            if(cameraOverLayer==nil)
            {
                cameraOverLayer=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 322, 424)];
            }
            [cameraOverLayer setImage:[UIImage imageNamed:overLayerName]];
            imagePicker.cameraOverlayView=cameraOverLayer;
            [self presentModalViewController:imagePicker animated:YES];
        }
            break;
        case 504://help
            break;
        case 505:       //保存图片
            if(mainImgView.image==nil)
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"Please take photo firstly" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            UIImageWriteToSavedPhotosAlbum(mainImgView.image, self, nil, nil);
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"Image has been saved you your iPhone Photo Album" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
            break;
        case 506://Email
        {
            if(mainImgView.image==nil)
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"Please take photo firstly" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
           if(![MFMailComposeViewController canSendMail])
           {
               UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Failure" message:@"Your device doesn't support sending emails" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
               [alert show];
               [alert release];
               return;
           }
            MFMailComposeViewController *mcvc=[[[MFMailComposeViewController alloc] init] autorelease];
            [mcvc setMailComposeDelegate:self];
            [mcvc setSubject:@"Here's a great photo!"];
            NSString *body=@"Good";
            [mcvc setMessageBody:body isHTML:NO];
            [mcvc addAttachmentData:UIImagePNGRepresentation(mainImgView.image) mimeType:@"image/jpeg" fileName:@"pickerimage.png"];
            [self presentModalViewController:mcvc animated:YES];
        }
            break;
        case 507://Facebook分享
            if(mainImgView.image==nil)
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"Please take photo firstly" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            if (![[delegate facebook] isSessionValid]) {
                [[delegate facebook] authorize:permissions];
            } else {
                [self uploadPhoto];
            }
            break;
        default:
            break;
    }
}

-(void)updateControls
{
    if(mainImgView.image!=nil)
    {
        [btnFacebook setEnabled:YES];
        [btnEmail setEnabled:YES];
        [btnSave setEnabled:YES];
    }
    else
    {
        [btnFacebook setEnabled:NO];
        [btnEmail setEnabled:NO];
        [btnSave setEnabled:NO];
    }
}

-(void)hideImageView:(id)sender
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [sender setAlpha:0.0];
    [mainScrollView setAlpha:0.0];
    [UIView commitAnimations];
    [sender performSelector:@selector(setHidden:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.5];
    [mainScrollView performSelector:@selector(setHidden:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.5];
}

#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];    
    
//    [self performSelector:@selector(showWorkViewAfterDelay) withObject:nil afterDelay:1.0f];
    
    //程序的底图
    UIImageView *screenBgImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_bg.jpg"]];
    [screenBgImgView setFrame:CGRectMake(0, 0, 320, 480)];
    [screenBgImgView setUserInteractionEnabled:YES];
    [self.view addSubview:screenBgImgView];
    [screenBgImgView release];
    
    //主视图显示图片的容器
    mainScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(10 , 40, 300, 400)];
    [mainScrollView setContentSize:CGSizeMake(320, 480)];
    [mainScrollView setUserInteractionEnabled:YES];
    [mainScrollView setHidden:YES];
//    [mainScrollView.layer setShadowOffset:CGSizeMake(5, 3)];
//    [mainScrollView.layer setShadowOpacity:0.6];
//    [mainScrollView.layer setShadowColor:[UIColor blackColor].CGColor];
    [self.view addSubview:mainScrollView];
    
    btnClose=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnClose setBackgroundImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    [btnClose setFrame:CGRectMake(290, 27, 31, 31)];
    [btnClose setHidden:YES];
    [btnClose addTarget:self action:@selector(hideImageView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnClose];
    
    //主视图显示的图片
    mainImgView=[[UIImageView alloc]init];
    [mainImgView setFrame:CGRectMake(0, 0, 320, 480)];
    [mainImgView setBackgroundColor:[UIColor blackColor]];
    [mainImgView setUserInteractionEnabled:YES];
    [mainScrollView addSubview:mainImgView];

    
    //底部的8个按钮,用tag区分事件,500开始
    
    UIButton *btn4X6=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn4X6 setTag:503];
    [btn4X6 setFrame:CGRectMake(88, 240, 33, 40)];
    [btn4X6 setBackgroundImage:[UIImage imageNamed:@"4X6_01.png"] forState:UIControlStateNormal];
    [btn4X6 setBackgroundImage:[UIImage imageNamed:@"4X6_02.png"] forState:UIControlStateHighlighted];
    [btn4X6 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    btn4X6.layer.shadowOffset=CGSizeMake(8, 3);
    btn4X6.layer.shadowOpacity=0.6;
    btn4X6.layer.shadowColor=[UIColor blackColor].CGColor;
    [screenBgImgView addSubview:btn4X6];
    
    UIButton *btn3X5=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn3X5 setTag:502];
    [btn3X5 setFrame:CGRectMake(127, 250, 31, 38)];
    [btn3X5 setBackgroundImage:[UIImage imageNamed:@"3X5_01.png"] forState:UIControlStateNormal];
    [btn3X5 setBackgroundImage:[UIImage imageNamed:@"3X5_02.png"] forState:UIControlStateHighlighted];
    [btn3X5 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    btn3X5.layer.shadowOffset=CGSizeMake(8, 3);
    btn3X5.layer.shadowOpacity=0.6;
    btn3X5.layer.shadowColor=[UIColor blackColor].CGColor;
    [screenBgImgView addSubview:btn3X5];

    UIButton *btnSlider=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnSlider setFrame:CGRectMake(170, 250, 28, 38)];
    [btnSlider setTag:500];
    [btnSlider setBackgroundImage:[UIImage imageNamed:@"Slides_01.png"] forState:UIControlStateNormal];
    [btnSlider setBackgroundImage:[UIImage imageNamed:@"Slides_02.png"] forState:UIControlStateHighlighted];
    [btnSlider addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnSlider.layer.shadowOffset=CGSizeMake(8, 3);
    btnSlider.layer.shadowOpacity=0.6;
    btnSlider.layer.shadowColor=[UIColor blackColor].CGColor;
    [screenBgImgView addSubview:btnSlider];

    UIButton *btnNeg=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnNeg setFrame:CGRectMake(205, 240, 30, 40)];
    [btnNeg setTag:501];
    [btnNeg setBackgroundImage:[UIImage imageNamed:@"Negatives_01.png"] forState:UIControlStateNormal];
    [btnNeg setBackgroundImage:[UIImage imageNamed:@"Negatives_02.png"] forState:UIControlStateHighlighted];
    [btnNeg addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnNeg.layer.shadowOffset=CGSizeMake(8, 3);
    btnNeg.layer.shadowOpacity=0.6;
    btnNeg.layer.shadowColor=[UIColor blackColor].CGColor;
    [screenBgImgView addSubview:btnNeg];
        
    
    
    CGFloat height=23;
    CGFloat originY=457;
    
    UIButton *btnHelper=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnHelper setTag:504];
    [btnHelper setFrame:CGRectMake(0, originY, 80, height)];
    [btnHelper setBackgroundImage:[UIImage imageNamed:@"Help_01.png"] forState:UIControlStateNormal];
    [btnHelper setBackgroundImage:[UIImage imageNamed:@"Help_02.png"] forState:UIControlStateHighlighted];
    [btnHelper addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [screenBgImgView addSubview:btnHelper];
    
    btnSave=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnSave setTag:505];
    [btnSave setFrame:CGRectMake(btnHelper.frame.origin.x+btnHelper.frame.size.width, btnHelper.frame.origin.y, btnHelper.frame.size.width, height)];
    [btnSave setBackgroundImage:[UIImage imageNamed:@"Save_01.png"] forState:UIControlStateNormal];
    [btnSave setBackgroundImage:[UIImage imageNamed:@"Save_02.png"] forState:UIControlStateHighlighted];
    [btnSave addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [screenBgImgView addSubview:btnSave];
    
    btnEmail=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnEmail setTag:506];
    [btnEmail setFrame:CGRectMake(btnSave.frame.origin.x+btnSave.frame.size.width, btnHelper.frame.origin.y,  btnHelper.frame.size.width, height)];
    [btnEmail setBackgroundImage:[UIImage imageNamed:@"Email_01.png"] forState:UIControlStateNormal];
    [btnEmail setBackgroundImage:[UIImage imageNamed:@"Email_02.png"] forState:UIControlStateHighlighted];
    [btnEmail addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [screenBgImgView addSubview:btnEmail];
    
    btnFacebook=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnFacebook setTag:507];
    [btnFacebook setFrame:CGRectMake(btnEmail.frame.origin.x+btnEmail.frame.size.width, btnHelper.frame.origin.y,  btnHelper.frame.size.width, height)];
    [btnFacebook setBackgroundImage:[UIImage imageNamed:@"Facebook_01.png"] forState:UIControlStateNormal];
    [btnFacebook setBackgroundImage:[UIImage imageNamed:@"Facebook_02.png"] forState:UIControlStateHighlighted];
    [btnFacebook addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [screenBgImgView addSubview:btnFacebook];
    
    // Initialize permissions
//    permissions = [[NSArray alloc] initWithObjects:@"offline_access", nil];
    
    permissions = [[NSArray alloc] initWithObjects:@"publish_stream", nil];

}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self showWorkViewAfterDelay];
}

-(void)releaseData
{
    self.mainScrollView=nil;
//    self.imgWorkedViewController=nil;
    self.cameraOverLayer=nil;
    self.mainImgView=nil;
    self.permissions=nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self releaseData];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)showWorkViewAfterDelay
{
    //将截图的图片放入Worked控制器进行处理
    self.imgWorkedViewController=[[[ImageWorkedViewController alloc] init] autorelease];
    [imgWorkedViewController setImageProcessDelegate:self];
    [imgWorkedViewController refreshImageView];
    [self presentModalViewController:imgWorkedViewController animated:YES];
}

#pragma UIimagePicker委托
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    //获取拍摄的照片，根据选择的相框大小进行截图操作        
    UIImage *tmpImage=[image fixOrientation];
    CGFloat widthScale=tmpImage.size.width/320;
    CGFloat heightScale=tmpImage.size.height/427;

    CGRect targetRect=CGRectMake(0, 0, 0, 0);
    switch (photoType) {
        case PhotoSlidersType:
        {
            targetRect=kRectSlider;
        }
            break;
        case PhotoNegativeType:
             targetRect=kRectNegative;
            break;
        case Photo35Type:
             targetRect=kRect35;
            break;
        case Photo46Type:
             targetRect=kRect46;
            break;
        default:
            break;
    }
    //放大后矩形的宽高和起点XY
    CGFloat rectOffsetX=targetRect.origin.x*widthScale;
    CGFloat rectOffsetY=targetRect.origin.y*heightScale;
    CGFloat scaledRectWidth=targetRect.size.width*widthScale;
    CGFloat scaledRectHeight=targetRect.size.height*heightScale;

    CGImageRef imageRef=CGImageCreateWithImageInRect(tmpImage.CGImage,CGRectMake(rectOffsetX,rectOffsetY,scaledRectWidth,scaledRectHeight));
    tmpImage=[UIImage imageWithCGImage:imageRef scale:1 orientation:tmpImage.imageOrientation];

    //将截取的照片放置到主屏幕上，更新按钮状态
    [mainImgView setImage:tmpImage];

    NSData *data=UIImagePNGRepresentation(tmpImage);
    [data writeToFile:kPhotoedImagePath atomically:YES];
    
    [self updateControls];
    
    [picker dismissModalViewControllerAnimated:YES];
    

    self.hudView=[[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    [self.view addSubview:hudView];
    hudView.labelText=@"Processing...";
    [hudView show:YES];
    [hudView hide:YES afterDelay:2.0f];
    
    //等待一会,然后显示处理图片的控制器
    [self performSelector:@selector(showWorkViewAfterDelay) withObject:nil afterDelay:1];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma 处理完image返回的结果
-(void)ImageProcessedFinished:(UIImage *)resultImage
{
    [mainImgView setImage:resultImage];
    [self isShowImageView:YES];
}

-(void)isShowImageView:(BOOL)flag
{
    if(flag)
    {
        [btnClose setAlpha:1.0];
        [mainScrollView setAlpha:1.0];
        [btnClose setHidden:NO];
        [mainScrollView setHidden:NO];
    }
    else {
        [btnClose setAlpha:0];
        [mainScrollView setAlpha:0];
        [btnClose setHidden:YES];
        [mainScrollView setHidden:YES];
        [mainImgView setImage:nil];
    }
}

#pragma MFmailCompostController的回调
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    if(error!=nil)
    {
        NSLog(@"%@",error);
    }
    NSString *message=@"";
    if(result==MFMailComposeResultSent)
    {
       message=@"Send Email Success!";
    }
    
    if(result==MFMailComposeResultFailed)
    {
        message=@"Sorry!Send Email Failed!";
    }
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    [self isShowImageView:NO];
    [mainImgView setImage:nil];
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - FBSessionDelegate Methods
/**
 * Called when the user has logged in successfully.
 */
- (void)fbDidLogin {
    //    [self showLoggedIn];
    
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [self storeAuthData:[[delegate facebook] accessToken] expiresAt:[[delegate facebook] expirationDate]];
    
    //    [pendingApiCallsController userDidGrantPermission];
}


-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSLog(@"token extended");
    [self storeAuthData:accessToken expiresAt:expiresAt];
}

/**
 * Called when the user canceled the authorization dialog.
 */
-(void)fbDidNotLogin:(BOOL)cancelled {
    //    [pendingApiCallsController userDidNotGrantPermission];
}

/**
 * Called when the request logout has succeeded.
 */
- (void)fbDidLogout {
    //    pendingApiCallsController = nil;
    
    // Remove saved authorization information if it exists and it is
    // ok to clear it (logout, session invalid, app unauthorized)
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"FBAccessTokenKey"];
    [defaults removeObjectForKey:@"FBExpirationDateKey"];
    [defaults synchronize];
    
//    [self showLoggedOut];
}

/**
 * Called when the session has expired.
 */
- (void)fbSessionInvalidated {
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:@"Auth Exception"
                              message:@"Your session has expired."
                              delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil,
                              nil];
    [alertView show];
    [alertView release];
    [self fbDidLogout];
}

#pragma mark - FBRequestDelegate Methods
/**
 * Called when the Facebook API request has returned a response.
 *
 * This callback gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
    //NSLog(@"received response");
}

- (void)apiGraphUserPermissions {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [[delegate facebook] requestWithGraphPath:@"me/permissions" andDelegate:self];
}

/**
 * Called when a request returns and its response has been parsed into
 * an object.
 *
 * The resulting object may be a dictionary, an array or a string, depending
 * on the format of the API response. If you need access to the raw response,
 * use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(FBRequest *)request didLoad:(id)result {
    NSLog(@"%@",result);

    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"Upload Success!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    [hudView hide:YES];
    [self isShowImageView:NO];
    if ([result isKindOfClass:[NSArray class]]) {
        result = [result objectAtIndex:0];
    }
    // This callback can be a result of getting the user's basic
    // information or getting the user's permissions.
    if ([result objectForKey:@"name"]) {
        // If basic information callback, set the UI objects to
        // display this.
        //        nameLabel.text = [result objectForKey:@"name"];
        NSLog(@"%@", [result objectForKey:@"name"]);
//        // Get the profile image
//        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[result objectForKey:@"pic"]]]];
//        
//        // Resize, crop the image to make sure it is square and renders
//        // well on Retina display
//        float ratio;
//        float delta;
//        float px = 100; // Double the pixels of the UIImageView (to render on Retina)
//        CGPoint offset;
//        CGSize size = image.size;
//        if (size.width > size.height) {
//            ratio = px / size.width;
//            delta = (ratio*size.width - ratio*size.height);
//            offset = CGPointMake(delta/2, 0);
//        } else {
//            ratio = px / size.height;
//            delta = (ratio*size.height - ratio*size.width);
//            offset = CGPointMake(0, delta/2);
//        }
//        CGRect clipRect = CGRectMake(-offset.x, -offset.y,
//                                     (ratio * size.width) + delta,
//                                     (ratio * size.height) + delta);
//        UIGraphicsBeginImageContext(CGSizeMake(px, px));
//        UIRectClip(clipRect);
//        [image drawInRect:clipRect];
//        UIImage *imgThumb = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        //        [profilePhotoImageView setImage:imgThumb];
        
        [self apiGraphUserPermissions];
    } else {
        // Processing permissions information
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [delegate setUserPermissions:[[result objectForKey:@"data"] objectAtIndex:0]];
    }
}

/**
 * Called when an error prevents the Facebook API request from completing
 * successfully.
 */
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    [hudView hide:YES];
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"Upload Failed!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    NSLog(@"Err message: %@", [[error userInfo] objectForKey:@"error_msg"]);
    NSLog(@"Err code: %d", [error code]);
}

@end
